package com.bing.common;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 消息编解码器
 */
public class MessageCodec extends MessageToMessageCodec<String, Message> {

    private static final Logger logger = LoggerFactory.getLogger(MessageCodec.class);
    private final Gson gson;

    public MessageCodec() {
        // 创建Gson实例，支持日期格式
        this.gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        try {
            // 将消息对象转换为JSON字符串
            String json = gson.toJson(msg);
            logger.debug("编码消息: {}", json);
            out.add(json);
        } catch (Exception e) {
            logger.error("消息编码异常", e);
            throw e;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, String json, List<Object> out) throws Exception {
        try {
            // 将JSON字符串转换为消息对象
            logger.debug("解码消息: {}", json);
            Message msg = gson.fromJson(json, Message.class);
            out.add(msg);
        } catch (Exception e) {
            logger.error("消息解码异常: {}", json, e);
            throw e;
        }
    }
}